package com.zj.user.controller;

import com.netflix.discovery.shared.resolver.ResolverUtils;
import com.zj.user.domain.User;
import com.zj.user.enums.RoleEnum;
import com.zj.user.enums.UserEnum;
import com.zj.user.service.UserService;
import com.zj.user.utils.MD5Util;
import com.zj.user.utils.ResultVoUtil;
import com.zj.user.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Objects;

/**
 * @Auther: zj
 * @Date: 2018/12/3 15:01
 * @Description:
 */
@RestController
public class RegisterController {

    @Autowired
    UserService userService;

    /**
     * 用户注册(只能注册普通用户)
     * @return
     */
    @PostMapping("/auth/register")
    public ResultVo authUserRegister(@RequestParam("username") String username,
                                     @RequestParam("password") String password,
                                     @RequestParam("inputVerify") String inputVerify) {

        //获取当前线程绑定的request对象
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        // 不分区大小写
        // 这个validateCode是在servlet中存入session的名字
        String validateCode = ((String) request.getSession().getAttribute("validateCode")).toLowerCase();
        inputVerify = inputVerify.toLowerCase();

        System.out.println("验证码：" + validateCode + "用户输入：" + inputVerify);

        //校验验证码
        if (!Objects.equals( validateCode, inputVerify )) {
            return ResultVoUtil.error( UserEnum.USER_CODE_IS_ERROR.getMessage() );
        }

        User user = userService.findOneUserByUsername( username );
        if (user != null) {
            return ResultVoUtil.error( UserEnum.USER_HASEXISTED.getMessage());
        }

        User newUser = new User();
        newUser.setUsername( username );
        newUser.setPassword( MD5Util.encode( password ));
        newUser.setRole( RoleEnum.User.getMessage() );
        newUser.setCreateTime( new Date() );
        newUser.setEmail( "#" );
        newUser.setHasFreeze( 0 );
        userService.UpDate( newUser );

        return ResultVoUtil.success("注册成功！");

    }

}
